package dl.database.connector;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Logger;

public class DbConnector {

	private final static Logger logger = Logger.getLogger(DbConnector.class
			.getName());

	private static DbConnector singleDbConnectorInstance;

	private String dbUser;
	private String dbPassword;
	private String dbServer;
	private String dbPort;
	private String dbName;

	private Connection connection = null;

	private String driverName = "org.postgresql.Driver";

	private String connectionUrl;

	private ResourceBundle rb = ResourceBundle.getBundle("dbConnection");

	private DbConnector() {
	}

	public static DbConnector getInstance() {
		if (singleDbConnectorInstance == null) {
			singleDbConnectorInstance = new DbConnector();
		}
		return singleDbConnectorInstance;
	}

	public Connection connect() {
		try {
			logger.info("Reading ResourceBundle : dbConnection");

			dbName = rb.getString("dbName");
			dbUser = rb.getString("dbUser");
			dbPassword = rb.getString("dbPassword");
			dbServer = rb.getString("dbServer");
			dbPort = rb.getString("dbPort");

			connectionUrl = "jdbc:postgresql://" + dbServer + ":" + dbPort
					+ "/" + dbName;

			logger.info("Get Connection : " + driverName);
			Class.forName(driverName);

			connection = DriverManager.getConnection(connectionUrl, dbUser,
					dbPassword);
		} catch (SQLException e) {
			logger.warning("Connection cannot be created. SQLException."
					+ e.getMessage());
		} catch (ClassNotFoundException e) {
			logger.warning("Class Not Found." + e.getMessage());
		}
		return connection;
	}

	public void disconnect() {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			logger.warning("Connection cannot be closed. SQLException."
					+ e.getMessage());
		}

	}

}
